package com.ikun.common.utils;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * @ClassName CaptchaUtil
 * @Description: 验证码生成工具
 * @Author: ximeng
 * @CreateDate: 2024/1/17 15:58
 * @UpdateUser:
 * @UpdateDate: 2024/1/17 15:58
 * @UpdateRemark:
 * @Version: 1.0
 */


public class CaptchaUtil {
    private static final int DEFAULT_WIDTH = 200;
    private static final int DEFAULT_HEIGHT = 50;

    public static byte[] generateCaptchaImage(String code, int width, int height) {
        Properties properties = new Properties();

        properties.setProperty("kaptcha.textproducer.char.length", String.valueOf(code.length()));
        // 图片边框
        properties.setProperty("kaptcha.border", "yes");
        // 边框颜色
        properties.setProperty("kaptcha.border.color", "105,179,90");
        // 字体颜色
        properties.setProperty("kaptcha.textproducer.font.color", "green");
        // 图片宽
        properties.setProperty("kaptcha.image.width", String.valueOf(width));
        // 图片高
        properties.setProperty("kaptcha.image.height", String.valueOf(height));
        // 字体大小
        properties.setProperty("kaptcha.textproducer.font.size", "30");
        // session key
        properties.setProperty("kaptcha.session.key", "code");
        Config config = new Config(properties);
        DefaultKaptcha kaptcha = new DefaultKaptcha();
        kaptcha.setConfig(config);

        BufferedImage image = kaptcha.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "png", outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return outputStream.toByteArray();
    }

    public static byte[] generateCaptchaImage(String code) {
        return generateCaptchaImage(code, DEFAULT_WIDTH, DEFAULT_HEIGHT);
    }

}
